//
//  NSString+DZCategory.m
//  Meidaojia
//
//  Created by Darren on 15/5/20.
//  Copyright (c) 2015年 Darren Zheng. All rights reserved.
//

#import "NSString+DZCategory.h"
#import <CommonCrypto/CommonDigest.h>

@implementation NSString (DZCategory)


- (NSString *)MD5String {
    const char *cstr = [self UTF8String];
    unsigned char result[16];
    CC_MD5(cstr, (CC_LONG)strlen(cstr), result);
    
    return [NSString stringWithFormat:
            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];  
}

- (CGSize)sizeForMaxWidth:(CGFloat)width
                     font:(UIFont *)font
{
    return [self sizeForMaxWidth:width font:font numberOfLines:0];
}

- (CGSize)sizeForMaxWidth:(CGFloat)width
                     font:(UIFont *)font
            numberOfLines:(int)numberOfLines
{
    CGRect rect = [self boundingRectWithSize:CGSizeMake(width, numberOfLines == 0 ? CGFLOAT_MAX : [font pointSize] * (numberOfLines + 1))
                                     options:NSLineBreakByWordWrapping | NSStringDrawingUsesLineFragmentOrigin
                                  attributes:@{NSFontAttributeName: font}
                                     context:nil];
    rect.size.width = ceil(rect.size.width);
    rect.size.height = ceil(rect.size.height);
    return rect.size;
    //
    //        UILabel *gettingSizeLabel = [[UILabel alloc] init];
    //        gettingSizeLabel.font = font;
    //        gettingSizeLabel.text = self;
    //        gettingSizeLabel.numberOfLines = numberOfLines;
    //        CGSize maximumLabelSize = CGSizeMake(width, CGFLOAT_MAX);
    //        CGSize expectSize = [gettingSizeLabel sizeThatFits:maximumLabelSize];
    //        return expectSize;
}

- (CGSize)sizeWithFont:(UIFont *)font
{
    return [self sizeWithAttributes:@{NSFontAttributeName:font}];
}

- (NSMutableDictionary *)queryComponents
{
    NSArray *queryComp = [self componentsSeparatedByString:@"&"];
    NSMutableDictionary *parameters = [NSMutableDictionary new];
    for (NSString *component in queryComp) {
        NSArray *subcomponents = [component componentsSeparatedByString:@"="];
        [parameters setObject:[[subcomponents objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
                       forKey:[[subcomponents objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    return parameters;
}

@end
